﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mailias.UI.Web.Infrastructure;
using Mailias.UI.Web.Models;

namespace Mailias.UI.Web.Controllers
{
    public class MailiasSettingsController : BaseDocumentStoreController
    {
        //
        // GET: /SmtpServerSettings/

        public ActionResult Index()
        {
            return View(MailiasSettingsViewModel.Create(DocumentSession.Query<MailiasSettings>().SingleOrDefault()));
        }

        [HttpPost]
        public ActionResult Index(MailiasSettingsViewModel viewModel )
        {
            try
            {
                var document = DocumentSession.Query<MailiasSettings>().SingleOrDefault();
            
                if (document != null)
                {
                    document.SmtpSettings.Address = viewModel.SmtpSettings.Address;
                    document.SmtpSettings.Port = viewModel.SmtpSettings.Port;
                }
                else
                {
                    document = viewModel.CreateSmtpServerSettings();
                    DocumentSession.Store(document);
                }

                return RedirectToAction("Index", "MailiasSettings");
            }
            catch (Exception)
            {
            }

            return View(viewModel);
        }

        public string SMTPListenAddress()
        {
            var document = DocumentSession.Query<MailiasSettings>().SingleOrDefault();

            if (document != null)
            {
                return document.SmtpSettings.Address;
            }

            return string.Empty;
        }

        public string SMTPListenPort()
        {
            var document = DocumentSession.Query<MailiasSettings>().SingleOrDefault();

            if (document != null)
            {
                return document.SmtpSettings.Port.ToString();
            }

            return string.Empty;
        }

    }
}
